package servlets;

import beans.BeanUsuario;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * Este Servlet trata do logoff de um usuário no ambiente
 * virtual da UAB-UFSCar
 */
public class ServletLogoff extends HttpServlet
{
    /**
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try
        {
            HttpSession sessao = request.getSession(true); //Obtém a sessão do cliente
            BeanUsuario usr= (BeanUsuario) sessao.getAttribute("loginAgenda"); //Obtêm login do usuário
            
            Cookie cookieUltimoAcesso = null;
            Cookie[] cookies = request.getCookies();
            for (int i = 0; i < cookies.length; i++) {        
                //armazena coockie existente específico do usuário no objeto cookieUltimoAcesso
                if ((cookies[i].getName()).compareTo("ultimoAcesso_" + usr.getId()) == 0) {                                       
                    cookieUltimoAcesso = cookies[i];
                    break;   
                }
            }
            //armazena data/hora atual em 'data'
            SimpleDateFormat dataFormatada = new SimpleDateFormat("dd/MM/yyyy - HH:mm:ss");
            String data = dataFormatada.format(new Date(System.currentTimeMillis()));
            //seta valor do cookie do usuário
            cookieUltimoAcesso.setValue(data); 
            cookieUltimoAcesso.setMaxAge(2*24*60*60); //Define que o cookie persistirá por 2 dias                    
            response.addCookie(cookieUltimoAcesso);   //Envia o outro cookie para o cliente           
            sessao.removeAttribute("loginAgenda"); //remove o objeto Usuário da sessão
            response.sendRedirect("login.jsp");//redireciona para login
        } finally {
            out.close();
        }
    }

    // <editor-fold defaultstate="collapsed" desc="Métodos HttpServlet. Clique no sinal de + à esquerda para editar o código.">
    /**
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
